package streaming;

import java.util.Random;

import simulation.AttendRequest;
import simulation.Logs;

public class Attacker5_Polluter extends Host {

	public Attacker5_Polluter(int newId) {
		super(newId);
	}

	public void handleRequest(int seqNo, Host source, boolean cm) {
		Logs.printMessage("handleRequest", "[MSG04a] Polluter peer " + this.getId() + " received request of chunk " + seqNo + " from peer " + source.getId());
		
		// Check if has the request seqNo - if is in availability window
		if (!availabilityWindow.isWithin(seqNo)){
			Logs.printMessage("handleRequest", "[MSG4b] Polluter peer " + this.getId() + " received request of chunk " + seqNo + " from peer " + source.getId() + ". OUTSIDE AVAILABILITY WINDOW.");
			return;
		}
		
		int index = availabilityWindow.calculateOffset(seqNo);

		Random random = new Random();
		
		// If peer is configured to pollute every chunk, do it
		if (StreamingConfig.ALWAYS_POLLUTE){
			requestedQueue.add(new AttendRequest(this, seqNo, "Chunk " + seqNo + " modified.", source, cm));
		}
		else { // otherwise, it pollutes randomly
			// This peer may pollute or not the system. The chances are 50-50 to being true, to pollute, or false, to not pollute
			if (random.nextBoolean()){
				requestedQueue.add(new AttendRequest(this, seqNo, "Chunk " + seqNo + " modified.", source, cm));
			}
			else {
				// Add request to the queue of requests
				requestedQueue.add(new AttendRequest(this, seqNo, chunks.get(index).getData(), source, cm));
			}
		}
	}
	
}
